package cn.tmall.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;



@WebFilter("/BackServletFilter")
public class BackServletFilter implements Filter {

    public BackServletFilter() {
        
    }

	
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest rq = (HttpServletRequest) request;
		HttpServletResponse rs = (HttpServletResponse) response;
		
		String contextPath = rq.getServletContext().getContextPath();
		String uri = rq.getRequestURI();
		uri = StringUtils.remove(uri, contextPath);
		if(uri.startsWith("/admin_")){
			String servletPath=StringUtils.substringBetween(uri,"_", "_")+"Servlet";
			String method = StringUtils.substringAfterLast(uri,"_");
			request.setAttribute("method", method);
			request.getRequestDispatcher("/"+servletPath).forward(rq, rs);
			return;
		}
		
		chain.doFilter(rq, rs);
	}

	
	public void init(FilterConfig fConfig) throws ServletException {
		
	}



	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}
